package com.jdkreader.concurrency.concurrent.pipeline;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class Assembler implements Runnable{

    //最多同时装配4辆车
    private CyclicBarrier cyclicBarrier=new CyclicBarrier(4);

    private Car car;

    private CarQueue chassisQueue,finishingQueue;

    private RobotPool pool;

    public CyclicBarrier barrier(){
        return cyclicBarrier;
    }

    public Car car(){
        return car;
    }

    public Assembler(CarQueue cq,CarQueue fq,RobotPool rp){
        chassisQueue=cq;
        finishingQueue=fq;
        pool=rp;
    }

    public void run(){

        try{
            while(!Thread.interrupted()){
                car=chassisQueue.take();
                //分派机器人进行不同的组装操作
                pool.hire(EngineRobot.class,this);
                pool.hire(DriveTrainRobot.class,this);
                pool.hire(WheelRobot.class,this);
                cyclicBarrier.await();
                finishingQueue.put(car);
            }
        }catch(InterruptedException e){
            System.out.println("Exiting Assembler via interrupt");
            e.printStackTrace();
        }catch(BrokenBarrierException e){
            throw new RuntimeException(e);
        }

        System.out.println("Assemble off");
    }
}
